//
//  HMOAuthViewController.swift
//  微博
//
//  Created by 郭鉴增 on 2016/12/5.
//  Copyright © 2016年 郭鉴增. All rights reserved.
//

import UIKit
import SVProgressHUD
//新浪微博用于标示我们创建应用的唯一ID
let AppKey = "2329946323"
//微博的APPsecret
let AppSecret = "5fbd9458596c750c27ab1aa2b58b062b"

//授权回调页
let Redirect_uri = "http://www.itcast.cn"

class HMOAuthViewController: UIViewController {

    //MARK: - 懒加载
    private lazy var webView : UIWebView = UIWebView()
    
    override func loadView() {
        //自定义视图
        webView.delegate = self
        view = webView
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setNavUIv()
        loadRequest()
    }
    //设置导航栏按钮
    private func setNavUIv() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.title = "微博登录"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        
    }
    //MARK: - 取消按钮点击
    @objc private func cancelAction() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    //MARK: - 自动填充点击
    @objc private func autoFillAction() {
        //执行jacasript
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '17301052217'; document.getElementById('passwd').value = 'z130217'")
    }
    
    //加载微博登录
    private func loadRequest() {
        //      定义接口url
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_uri)"
        //创建请求对象
        let urlRequest = URLRequest(url: URL(string: url)!)
        //加载请求
        webView.loadRequest(urlRequest)
    }
    

}

extension HMOAuthViewController:UIWebViewDelegate {
    
    //将要加载请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //如果url地址为nil  不加载这次请求,返回false
        guard let url = request.url else{
            return false
        }
        //代码到此 ,url不为nil
        //取反不是我们的关心的回调页的地址
        if !url.absoluteString.hasPrefix(Redirect_uri) {
            return true
        }
        //代码执行到此,表示是我们回调页大头的请求地址
        //query 表示获取请求的参数
        if let query =  url.query,query.hasPrefix("code=") {
            //使用需要截取的code参数
            let startIndex = "code=".endIndex
            //截取code
            let code = query.substring(from: startIndex)
            print(code)
            
            //通过code获取acesstoken
            
            HMUserAccountViewModel.sharedUserAccount.requestAccessToken(code: code, callBack: { (isSuccess) in
                if isSuccess {
//                    表示登陆成功
                    print("登录成功")
                    self.dismiss(animated: false, completion: { 
                        //切换到欢迎页面
                        //必须等到dismiss操作完成以后再去发送通知切换跟视图控制器,否则持有访客视图控制器
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotifationName), object: self)
                    })
                    
                    
                }else {
                    print("登录失败")
                }
            })
        } else {
            //点击取消授权的按钮
            dismiss(animated: true, completion: nil)
        }
        
        //不加载页面
        return false
    }
    
    //已经开始加载请求
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
}


